/**
 * 生之短插件
 * crstudio@qq.com
 */

var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth()+1;
var currentDay = date.getDay();
var currentHour = date.getHours();
var currentMinute = date.getMinutes();
var currentSecond = date.getSeconds();

var now = Math.floor(date.getTime()/1000);
var lifeYear = localStorage.getItem('lifeYear') ? localStorage.getItem('lifeYear') : 70;
var birthDate = localStorage.getItem('birthDate');
if(birthDate == null || typeof birthDate === 'undefined'){
    var birthTime = now - 25 * 365.25 * 24 * 3600;
    var currentAge = 25;
}else{
    var birthTime = Math.floor(new Date(birthDate).getTime()/1000);
    var currentAge = Math.floor((now - birthTime)/365.25);
}

var weekday =["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
var age = 0;
var lifeSecond = Math.floor(lifeYear * 365.25 * 24 * 3600); //寿命的秒数 算上闰年, 一年平均365.25天
var passSecond = now - birthTime;
var age_label = ['十', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
var W = document.body.clientWidth;
var H = document.body.clientHeight;


$(function() {
    clock();
    renderCalendar();
    birthSelect();
    getWeather();
    localStorage.slogan = '你好, 世界';
});

/**
 * 天气接口
 */
function getWeather() {
    let msg = '';
    $.get('https://www.tianqiapi.com/api/', function (res) {
        if(res.hasOwnProperty('city')){
            msg += res.city;
            msg += res.data[0].wea;
            msg += res.data[0].tem;
            msg += res.data[0].tem1 + '/' + res.data[0].tem2;
        }
        $('#weather').html(msg);
    });
}


/**
 * 同步信息
 */
function sysInfo()
{
    chrome.storage.sync.get(['birthday'], function(result) {
        localStorage.birthday = result.birthday;
    });

    chrome.storage.sync.get(['lifeYear'], function(result) {
        localStorage.lifeYear = result.lifeYear;
    });

    chrome.storage.sync.get(['slogan'], function(result) {
        localStorage.slogan = result.slogan;
    });
}

/**
 * 事件绑定
 */
$('.btn-setting').click(function(){
    $('.setting').toggle("fast");
});
$('.wrapper').click(function(){
    $('.setting').hide();
});
$('.left form input').focus(function(){
    $('.right').hide();
    $('.left').animate({width:'600px'}, 200);
});
$('.right form input').focus(function(){
    $('.left').hide();
    $('.right input').css({'text-align':'left'});
    $('.right').animate({width:'600px'}, 200);
});
$('.search form input').blur(function(){
    $('.left').css({width:'296px'}).show();
    $('.right').css({width:'296px'}).show();
    console.log($('.right input[type="text"]').val());
    if(!$('.right input[type="text"]').val()){
        $('.right input[type="text"]').css({'text-align':'right'});
    }
});

/**
 * 渲染日历
 */
function renderCalendar(){
    if (localStorage.birthday) {
        birthYear = new Date(localStorage.birthday).getFullYear();
        $('#birthYear').val(birthYear);
    }
    
    if (localStorage.lifeYear) {
        lifeYear = localStorage.lifeYear;
        $('#lifeYear').val(lifeYear);
    }

    if (localStorage.slogan) {
        $('#slogan').val(localStorage.slogan);
        $('#ipt-slogan').text(localStorage.slogan.toString());
    }

    $('#lifeCalendar').width(lifeYear * 2.2  + 'vh');
    $('#lifeCalendar').html('');
    for (var i = 1; i <= lifeYear; i++) {
        age = toAge(i);
        var str_year = '<dl><dt>' + age + '</dt><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd><dd></dd></dl>'
        $('#lifeCalendar').append(str_year);
    }
    passCalendar();
}

/**
 * 降低过去月份的透明度
 */
function passCalendar() {
    if (localStorage.birthday) { birthYear = new Date(localStorage.birthday).getFullYear()}
    if (localStorage.lifeYear) { lifeYear = localStorage.lifeYear }

    var passMonth = (currentAge - 1) * 12 + currentMonth;
    
    $('#lifeCalendar dd').each(function(i, item){
        if(i < passMonth){
            $(item).css({opacity:0.05});
        }
    });
}

/**
 * 搜索建议
 */
$('.search input[type=search]').on('input', function (t) {
    let q = $(this).val();
    var sugurl = "http://suggestion.baidu.com/su?p=3&wd="+q+"&ie=UTF-8&cb=&callback=";
    // $.getJSON(sugurl, function (res) {
    //
    // });

    var xhr=new XMLHttpRequest();
    xhr.open('get', sugurl);
    // xhr.setRequestHeader("Origin", '');
    xhr.send();


    //定义回调函数
    // window.baidu = {
    //     sug: function(json) {
    //         console.log(json)
    //     }
    // };

    //动态添加JS脚本
    // var script = document.createElement("script");
    // script.src = sugurl;
    // document.getElementsByTagName("head")[0].appendChild(script);


    // $.ajax({
    //     url: 'http://suggestion.baidu.com/su',
    //     type: 'get',
    //     dataType: "jsonp",
    //     data: {p: 3, ie: 'UTF-8', cb: '', wd: q},
    //     success: function (res) {
    //         // console.log(res);
    //     }
    // });
});


/**
 * 保存设置
 */
$('.save').click(function() {
    var birthday  = $('input[name=birthday]').val();
    var lifeYear = Number($('input[name=lifeYear]').val());
    var slogan = $('input[name=slogan]').val();
    var currentYear = date.getFullYear();

    birthTime = new Date(birthDate).getTime();

    if(birthDay < currentYear-80 || birthYear > currentYear-10) {
        alert('请填写正确的出生年份!');
    }
    if(lifeYear < 45 || lifeYear > 70){
        alert('本应用的支持的退休年龄范围为45~70岁!');
    }
    if((birthDay+lifeYear)<=currentYear){
        alert('请填写合适的出生年份和预期寿命!');
    }

    localStorage.slogan = slogan;
    localStorage.birthDate = birthDate;
    localStorage.lifeYear = lifeYear;

    chrome.storage.sync.set({'slogan': slogan});
    chrome.storage.sync.set({'birthDate': birthDate});
    chrome.storage.sync.set({'lifeYear': lifeYear});

    $('.setting').hide('middle');
    renderCalendar();
});

/**
 * 年龄转换函数
 * @param n
 * @returns {string}
 */
function toAge(n){
   if(n === 1 || n%10 === 0){
       if(n > 15){
           age = age_label[Math.floor(n/10)] + '十';
           if(n%10 > 0)
               age += age_label[n%10];
       }else if(n === 15){
           age = '十五';
       }else{
           age = age_label[n];
       }
       return age;
   }
   return '';
}

/**
 * 生日选择
 */
$('#birthYear').on('click', function () {
    renderBirthDay();
});
$('#birthMonth').on('click', function () {
    renderBirthDay();
});
renderBirthDay();
function birthSelect() {
    let y = parseInt(currentYear);
    let str = "";
    for (let i = 8; i <= 50; i++){
        str = str + "<option value='"+(y-i)+"'>"+(y-i)+"</option>"
    }
    $('#birthYear').html(str);
}
function renderBirthDay() {
    let y = parseInt($('#birthYear').val());
    let m = parseInt($('#birthMonth').val());
    if(m == null || typeof m === 'undefined')
        m = 1;

    if(m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12){
        days = 31;
    }else if(m === 2){
        if((y%4 === 0 && y%100 != 4) || y%400 === 0){
            days = 29;
        }else{
            days = 28;
        }
    }else{
        days = 30;
    }
    let str = '';
    for (let i = 1; i <= days; i++){
        str = str + '<option value="'+i+'">'+i+'</option>';
    }
    $('#birthDay').html(str);
}


/**
 * 钟表函数
 */
function clock(){
    var date = new Date();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    var y = date.getFullYear();
    var mo = date.getMonth()+1;
    var d = date.getDate();
    $('.hour').text(h);
    if(m<10) m = '0' + m;
    $('.minute').text(m);
    if(s<10) s = '0'+ s;
    $('.second').text(s);
    $('.year').text(y);
    $('.month').text(mo);
    $('.day').text(d);

    setTimeout('clock()', 1000);
}


/**
 * 人生钟表
 * @type {jQuery|HTMLElement}
 */
var lifeClock = $("#lifeClock");
function initNumXY(){
    // 1、12个数字的位置设置
    var radius = 100;//大圆半价
    var dot_num = 360/$(".dot").length;//每个div对应的弧度数
    //每一个dot对应的弧度;
    var ahd = dot_num*Math.PI/180;
    $(".dot").each(function(index, el) {
        $(this).css({
            "left":100+Math.sin((ahd*index))*radius,
            "top":100+Math.cos((ahd*index))*radius
        });
    });
    // 2、刻钟设置
    for(var i = 0; i < 60; i++) {
        lifeClock.innerHTML += "<div class='clock-scale'> " +
          "<div class='scale-hidden'></div>" +
          "<div class='scale-show'></div>" +
          "</div>";
    }
    var scale = $(".clock-scale");
    for(var i = 0; i < scale.length; i++) {
        scale[i].style.transform="rotate(" + (i * 6 - 90) + "deg)";
    }
}
initNumXY();//调用上面的函数
//获取时钟id
var hour_line = document.getElementById("hour_line"),
  minute_line = document.getElementById("minute_line"),
  second_line = document.getElementById("second_line");

//3、设置动态时间
function setLifeClock(){
    //一生相当于一天的时 分 秒
    var life_as_day = Math.floor(24*3600*passSecond/lifeSecond);
    console.log('life_as_day',life_as_day);
    var life_as_day_hour = Math.floor(life_as_day/3600);
    var life_as_day_minute = Math.floor((life_as_day-life_as_day_hour*3600)/60);
    var life_as_day_second = life_as_day - life_as_day_hour*3600 - life_as_day_minute*60;

    $('#lifeClockInfo').html("您的人生已经到了<br/> "+life_as_day_hour+"点"+life_as_day_minute+"分"+life_as_day_second+"秒");

    hour_deg = life_as_day_hour/12*360-90;
    minute_deg = life_as_day_minute/60*36-90;
    second_deg = life_as_day_second/60*360-90;
    //时分秒针设置
    hour_line.style.transform = 'rotate(' + hour_deg + 'deg)';
    minute_line.style.transform = 'rotate(' + minute_deg + 'deg)';
    second_line.style.transform = 'rotate(' + second_deg +'deg)';
}
setLifeClock();